package org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyHazardInvestigation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyRectificationInformation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyReviewInformation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.mapper.ZyHazardInvestigationMapper;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.mapper.ZyRectificationInformationMapper;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.mapper.ZyReviewInformationMapper;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.IZyHazardInvestigationService;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.vo.ZyHazardInvestigationFinishStatusVo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 中阳隐患排查信息
 * @Author: jeecg-boot
 * @Date:   2024-03-20
 * @Version: V1.0
 */
@Service
@Slf4j
public class ZyHazardInvestigationServiceImpl extends ServiceImpl<ZyHazardInvestigationMapper, ZyHazardInvestigation> implements IZyHazardInvestigationService {

	@Autowired
	private ZyHazardInvestigationMapper zyHazardInvestigationMapper;
	@Autowired
	private ZyRectificationInformationMapper zyRectificationInformationMapper;
	@Autowired
	private ZyReviewInformationMapper zyReviewInformationMapper;

	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Autowired
	private ISysUserService sysUserService;
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(ZyHazardInvestigation zyHazardInvestigation, List<ZyRectificationInformation> zyRectificationInformationList,List<ZyReviewInformation> zyReviewInformationList) {
		zyHazardInvestigationMapper.insert(zyHazardInvestigation);
		ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		 获取id，为了到发送超时提醒的时候查询记录
		String id = zyHazardInvestigation.getId();
		Date deadline = zyHazardInvestigation.getRectificationDeadline();
		long delay = deadline.getTime() - System.currentTimeMillis();

		ScheduledFuture<?> future = scheduler.schedule(() -> {
			// 在给定日期后执行的推送信息操作
			ZyHazardInvestigation zyHazardInvestigation1 = zyHazardInvestigationMapper.selectById(id);
			String result = zyHazardInvestigation1.getResult();
			String rectifierPerson = zyHazardInvestigation1.getRectifierPerson();
			SysUser sysUser = sysUserService.lambdaQuery().eq(SysUser::getRealname, rectifierPerson).one();

			if ("待整改".equals(result)){
				// 发送超时提醒
				System.out.println("发送超时提醒");
				LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				MessageDTO message = new MessageDTO(loginUser.getUsername(),sysUser.getUsername(),"发送超时提醒","任务已超时，请及时处理");
				sysBaseAPI.sendSysAnnouncement(message);
				log.info("发送成功");
			}
		}, delay, TimeUnit.MILLISECONDS);
		scheduler.shutdown();
		if(zyRectificationInformationList!=null && zyRectificationInformationList.size()>0) {
			for(ZyRectificationInformation entity:zyRectificationInformationList) {
				//外键设置
				entity.setParentId(zyHazardInvestigation.getId());
				entity.setStatus(zyHazardInvestigation.getRectifierStatus());
				zyRectificationInformationMapper.insert(entity);
			}
		}
		if(zyReviewInformationList!=null && zyReviewInformationList.size()>0) {
			for(ZyReviewInformation entity:zyReviewInformationList) {
				//外键设置
				entity.setParentId(zyHazardInvestigation.getId());
				entity.setStatus(zyHazardInvestigation.getReviewerStatus());
				zyReviewInformationMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(ZyHazardInvestigation zyHazardInvestigation,List<ZyRectificationInformation> zyRectificationInformationList,List<ZyReviewInformation> zyReviewInformationList) {
		zyHazardInvestigationMapper.updateById(zyHazardInvestigation);
		
		//1.先删除子表数据
//		zyRectificationInformationMapper.deleteByMainId(zyHazardInvestigation.getId());
		zyReviewInformationMapper.deleteByMainId(zyHazardInvestigation.getId());

		List<ZyRectificationInformation> riRecodes = zyRectificationInformationMapper.selectByMainId(zyHazardInvestigation.getId());

		//2.子表数据重新插入
		if(zyRectificationInformationList!=null && zyRectificationInformationList.size()>0) {
			for(ZyRectificationInformation entity:zyRectificationInformationList) {
				//外键设置
				entity.setParentId(zyHazardInvestigation.getId());
				if (riRecodes.size() == 0){
					zyRectificationInformationMapper.insert(entity);
				}else {
					LambdaQueryWrapper<ZyRectificationInformation> updatewrapper = new LambdaQueryWrapper<>();
					updatewrapper.eq(ZyRectificationInformation::getParentId, zyHazardInvestigation.getId());
					zyRectificationInformationMapper.update(entity,updatewrapper);
				}
			}
		}
		if(zyReviewInformationList!=null && zyReviewInformationList.size()>0) {
			for(ZyReviewInformation entity:zyReviewInformationList) {
				//外键设置
				entity.setParentId(zyHazardInvestigation.getId());
				zyReviewInformationMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		zyRectificationInformationMapper.deleteByMainId(id);
		zyReviewInformationMapper.deleteByMainId(id);
		zyHazardInvestigationMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			zyRectificationInformationMapper.deleteByMainId(id.toString());
			zyReviewInformationMapper.deleteByMainId(id.toString());
			zyHazardInvestigationMapper.deleteById(id);
		}
	}

    @Override
    public List<ZyHazardInvestigationFinishStatusVo> getFinishStatusVoList(String startDate, String endDate,String siteId) {
        List<ZyHazardInvestigationFinishStatusVo> dailyCorrectionStatusCount = zyHazardInvestigationMapper.getDailyCorrectionStatusCount(startDate, endDate,siteId);
        return dailyCorrectionStatusCount;
    }
	public List<ZyHazardInvestigationFinishStatusVo> getWeeklyFinishStatusVoList(String startDate, String endDate, String siteId) {
		Map<String, Object> params = new HashMap<>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		params.put("siteId", siteId);
		return zyHazardInvestigationMapper.getWeeklyCorrectionStatusCount(params);
	}
	public List<ZyHazardInvestigationFinishStatusVo> getMonthlyFinishStatusVoList(String startDate, String endDate, String siteId) {
		Map<String, Object> params = new HashMap<>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		params.put("siteId", siteId);
		return zyHazardInvestigationMapper.getMonthlyCorrectionStatusCount(params);
	}



}
